package com.xiaoyu.lanling.feature.coin.activity

import `in`.srain.cube.util.CLog
import `in`.srain.cube.util.log.LogEvent
import `in`.srain.cube.views.list.CubeRecyclerViewSimpleAdapter
import android.Manifest
import android.os.Bundle
import android.text.TextUtils
import androidx.appcompat.app.AlertDialog
import com.alibaba.security.realidentity.RPEventListener
import com.alibaba.security.realidentity.RPResult
import com.alibaba.security.realidentity.RPVerify
import com.tbruyelle.rxpermissions2.RxPermissions
import com.xiaoyu.base.app.GlobalUI
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.view.list.GridSpacingItemDecoration
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity
import com.xiaoyu.lanling.event.coin.CoinExchangeDetailEvent
import com.xiaoyu.lanling.event.coin.CoinExchangeListItemButtonClickEvent
import com.xiaoyu.lanling.event.coin.CoinExchangeListEvent
import com.xiaoyu.lanling.event.verify.GetFullVerifyTokenEvent
import com.xiaoyu.lanling.event.verify.VerifyConfirmEvent
import com.xiaoyu.lanling.event.verify.VerifyConfirmEvent.Companion.FACE_VERIFY
import com.xiaoyu.lanling.event.verify.VerifyConfirmEvent.Companion.FULL_VERIFY
import com.xiaoyu.lanling.feature.coin.data.CoinData
import com.xiaoyu.lanling.feature.coin.model.CoinExchangeItem
import com.xiaoyu.lanling.feature.coin.viewholder.CoinExchangeProductViewHolder
import com.xiaoyu.lanling.feature.verify.data.VerifyData
import com.xiaoyu.lanling.log.AppLogClient
import com.xiaoyu.lanling.router.Router
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_coin_exchange_list.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class CoinExchangeListActivity : AppCompatToolbarActivity() {

    private val requestTag = Any()
    private val adapter = CubeRecyclerViewSimpleAdapter<CoinExchangeItem>()

    private var mDisposable: Disposable? = null
    private var mBalance: Int? = null

    override fun onCreateSafelyAfterAppFinishInit(savedInstanceState: Bundle?) {
        super.onCreateSafelyAfterAppFinishInit(savedInstanceState)
        setLightStatusBar()
        setContentView(R.layout.activity_coin_exchange_list)
        initToolbar()

        initView()
        initAdapter()
        initEvent()
        initData()
    }

    override fun onDestroy() {
        super.onDestroy()
        mDisposable?.dispose()
    }

    private fun initView() {
        title = getString(R.string.coin_exchange_list_title)
    }

    private fun initAdapter() {
        adapter.setViewHolderClass(0, null, CoinExchangeProductViewHolder::class.java, 9)
        recyclerview.adapter = adapter
        recyclerview.addItemDecoration(GridSpacingItemDecoration(2, 16, true))
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: CoinExchangeListEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                showData(event)
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: CoinExchangeListItemButtonClickEvent) {
                mBalance?.let {
                    if (it >= event.item.costPoint) {
                        VerifyData.verifyConfirm(requestTag, event.item.id)
                    } else {
                        GlobalUI.getInstance().showToast(getString(R.string.coin_exchange_coin_not_enough_toast))
                    }
                }
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: VerifyConfirmEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                onVerifyConfirm(event)
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: GetFullVerifyTokenEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                verify(event.verifyToken)
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: CoinExchangeDetailEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                Router.instance.gotoCoinExchangeDetailActivity(this@CoinExchangeListActivity, event.item)
                finish()
            }
        })
    }

    private fun onVerifyConfirm(event: VerifyConfirmEvent) {
        when (event.result) {
            FACE_VERIFY -> showFaceVerifyDialog()
            FULL_VERIFY -> showFullVerifyDialog()
            else -> CoinData.productDetail(requestTag, event.productId)
        }
    }

    private fun showFaceVerifyDialog() {
        AlertDialog.Builder(this)
                .setMessage(getString(R.string.coin_exchange_list_face_verify_dialog_message))
                .setPositiveButton(R.string.coin_exchange_list_verify_dialog_positive_button) { _, _ ->
                    Router.instance.gotoVerifyHumanActivity(this)
                }
                .show()
    }

    private fun showFullVerifyDialog() {
        AlertDialog.Builder(this)
                .setMessage(getString(R.string.coin_exchange_list_full_verify_dialog_message))
                .setPositiveButton(R.string.coin_exchange_list_verify_dialog_positive_button) { _, _ ->
                    VerifyData.getFullVerifyToken(requestTag)
                }
                .show()
    }

    private fun showData(event: CoinExchangeListEvent) {
        mBalance = event.pointBalance
        balance.text = getString(R.string.coin_exchange_list_balance, event.pointBalance.toString())
        adapter.list = event.products
        adapter.notifyDataSetChanged()
    }

    private fun initData() {
        CoinData.exchangeProductList(requestTag)
    }

    private fun verify(verifyToken: String) {
        mDisposable = RxPermissions(this)
                .request(Manifest.permission.CAMERA)
                .filter { !TextUtils.isEmpty(verifyToken) }
                .subscribe { granted ->
                    if (granted) {
                        onVerify(verifyToken)
                    } else {
                        GlobalUI.getInstance().showToast("请授予相机权限后再试")
                    }
                }
    }

    private fun onVerify(verifyToken: String) {
        RPVerify.start(this, verifyToken, object : RPEventListener() {
            override fun onFinish(result: RPResult, code: String, message: String) {
                GlobalUI.getInstance().showToastForLong(result.message)

                val logEvent  = LogEvent("verifyFull")
                logEvent.putData("code", result.code)
                logEvent.putData("message", result.message)
                AppLogClient.instance.addLog(logEvent)
            }
        })
    }
}